<?php

namespace adminmatrix\server\app\middleware;
use adminmatrix\annotation\auth\IsPermission;
use app\Request;
use think\App;
use think\facade\Config;
use ReflectionClass;
class PermissionMiddleware
{
    public function handle(Request $request, \Closure $next)
    {
        // 执行下一个中间件或控制器
        $controller = str_replace('.', '\\', $request->controller());

        $controller_suffix = Config::get('route.controller_suffix') ? 'Controller' : '' ;
        $controller_layer  = !empty($controller_suffix) ? ucfirst($controller_suffix) : '';
        $appName = str_replace('/', '', $request->root());
        $controller = "\\app\\{$appName}\\controller\\" . $controller  . $controller_layer;

        if(class_exists($controller))
        {
            $reflect = new ReflectionClass($controller);

            $hasIsPermission = false;

            # 判断类上是否有 isPermission
            foreach ($reflect->getAttributes() as $attribute) {
                if (invoke($attribute->getName()) instanceof IsPermission) {
                    $hasIsPermission = true;
                    break;
                }
            }

            if (!$hasIsPermission) {
                # 类上没有，判断当前方法是否有
                $methodName = $request->action();
                $method = $reflect->getMethod($methodName);
                foreach ($method->getAttributes() as $attribute) {
                    if (invoke($attribute->getName()) instanceof IsPermission) {
                        $hasIsPermission = true;
                        break;
                    }
                }
            }

            $request->isNeedLogin = $hasIsPermission;
            return $next($request);
//        if ($request->header('token') !== null) halt($request->header('token'));
        }

        $class = invoke($controller);


    }
}